#! /usr/bin/env python
# -*- coding: utf-8 -*-
# vim:fenc=utf-8
#
# Copyright © 2020 crane <crane@sharp>
#
# Distributed under terms of the MIT license.

"""

"""

# LRUCache(3)
# set(1, 1)
# set(2, 2)
# set(3, 3)
# set(3, 3)
# get(3)
# get(3)
# get(2)
# get(1)
# set(5, 5)
# get(1)
# get(2)
# get(3)
# get(3)
# get(5)
# 您的打印日志
# id n 140282061632456 1
# head 1 1 n 2 2
# tail 1 1 n 2 2
# head 2 2 n 3 3
# 2 140282061632680
# tail 1 1 n 3 3
# head 3 3 n 3 3
# tail 2 2 n 3 3
# head 3 3 n 2 2
# tail 3 3 n 2 2
# head 2 2 n 5 5
# 2 140282061632680
# tail 3 3 n 5 5
# head 5 5 n 3 3
# tail 3 3 n 3 3
# head 3 3 n 3 3
# tail 2 2 n 3 3
# head 3 3 n 5 5
# tail 2 2 n 5 5
# 输出
# [3,3,2,-1,-1,-1,3,3,5]
# 期望答案
# [3,3,2,-1,-1,2,3,-1,5]
# 提示
# 请检查你的代码和算法正确性，WA通常是由错误的答案造成的，请思考一下你的算法是否正确。

import collections


class Node:
    def __init__(self, key, value, pre=None, next=None):
        self.key = key
        self.value = value

        if pre is None:
            pre = self
        if  next is None:
            next = self

        self.pre = pre
        self.next = next

    # def set_loop(self):
    #     self.pre = self
    #     self.next = self

    def link(self, other):
        self.next = other
        other.pre = self


    def show(self):
        return self.key


class LRUCache:
    """
    @param: capacity: An integer
    """
    def __init__(self, capacity):
        self.capacity = capacity

        self.cache = collections.OrderedDict()

    @property
    def len(self):
        return len(self.cache)

    def get(self, key):
        n = self.cache.get(key)
        if n is None:
            return -1

        # print('get before', key, self.len)
        result = n.value
        self.adjust_to_head(n)
        # print('get after', key, self.len)
        return result

    def set(self, key, value):
        n = self.cache.get(key)

        if n is None:
            n = Node(key, value)
            self.add_new_head(n)
        else:
            self.adjust_to_head(n)
            n.value = value

    def adjust_to_head(self, n):
        # self.cache.popitem(n.key)
        del self.cache[n.key]
        self.cache[n.key] = n       # 加到尾部, 最优

    def add_new_head(self, n):
        if self.len >= self.capacity:
            self.del_tail()

        self.cache[n.key] = n

        # self.valid()

    def del_tail(self):
        self.cache.popitem(last=False)      # 头部优先级最低, 弹出

    def valid(self):
        return True


def test():
    s = LRUCache(2)
    s.set(2, 222)
    s.set(1, 111)

    print('get 1', s.get(1))
    print('get 2', s.get(2))
    print('get 1', s.get(1))

    s.set(3, 333)

    print(s.get(1))
    print(s.get(2))
    print(s.get(3))

    s.set(5, 555)
    print('get 2', s.get(2))
    print('get 3', s.get(3))
    print('get 5', s.get(5))

def main():
    print("start main")
    test()

if __name__ == "__main__":
    main()
